package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.mongodb.client.result.UpdateResult;
import com.tanhua.dubbo.api.mongo.MovementApi;
import com.tanhua.dubbo.async.TimeLineService;
import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.MovementTimeLine;
import com.tanhua.model.vo.PageResult;
import org.apache.commons.lang3.RandomUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.ArrayList;
import java.util.List;

@DubboService
public class MovementApiImpl implements MovementApi {

    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private TimeLineService timeLineService;

    /**
     * 发布动态
     * @param movement
     */
    @Override
    public void publish(Movement movement) {
        movement.setPid(idWorker.getNextId("movement"));
        movement.setCreated(System.currentTimeMillis());
        mongoTemplate.insert(movement);

        timeLineService.saveTimeLine(movement.getUserId(), movement.getId());
    }

    /**
     * 查询动态
     * @param page
     * @param pageSize
     * @param userId
     * @return
     */
    @Override
    public PageResult<Movement> findByUserId(Long page, Long pageSize, Long userId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId))
                .with(Sort.by(Sort.Order.desc("created")));
        long count = mongoTemplate.count(query, Movement.class);
        List<Movement> movements = new ArrayList<>();
        long start = (page-1)*pageSize;
        if(count > start) {
            query.skip(start).limit(pageSize.intValue());
            movements = mongoTemplate.find(query, Movement.class);
        }
        return new PageResult(page, pageSize,count,movements);
    }

    /**
     * 获取好友动态
     * @param userId
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageResult<Movement> getMovementsByFriendId(Long userId, Long page, Long pageSize) {
        Query query = new Query();
        query.addCriteria(Criteria.where("friendId").is(userId));

        long count = mongoTemplate.count(query, MovementTimeLine.class);
        List<Movement> movements = new ArrayList<>();
        long skip = (page - 1) * pageSize;
        if(count > skip) {
            query.skip(skip).limit(pageSize.intValue())
                    .with(Sort.by(Sort.Direction.DESC, "created"));;
            List<MovementTimeLine> movementTimeLines = mongoTemplate.find(query, MovementTimeLine.class);
            List<ObjectId> movementIds = CollUtil.getFieldValues(movementTimeLines, "movementId", ObjectId.class);
            Query movementQuery = new Query(Criteria.where("_id").in(movementIds));
            movementQuery.with(Sort.by(Sort.Direction.DESC, "created"));
            movements = mongoTemplate.find(movementQuery, Movement.class);
        }
        return new PageResult(page, pageSize, count, movements);
    }

    /**
     * 随机动态
     * @param userId
     * @param pageSize
     * @return
     */
    @Override
    public List<Movement> randomMovement(Long userId, Long pageSize) {
        Query query = new Query(Criteria.where("userId").ne(userId));
        long count = mongoTemplate.count(query, Movement.class);
        if(count < 10) {
            return mongoTemplate.find(query, Movement.class);
        }

        long start = RandomUtils.nextLong(0, count - 9);
        query.skip(start).limit(10);
        return mongoTemplate.find(query, Movement.class);
    }

    /**
     * 通过pid获取动态列表
     * @param pidList
     * @return
     */
    @Override
    public List<Movement> getByPid(List<Long> pidList) {
        Query query = new Query(Criteria.where("pid").in(pidList))
                .with(Sort.by(Sort.Direction.DESC, "created"));
        return mongoTemplate.find(query, Movement.class);
    }

    /**
     * 根据动态id查询动态
     * @param id
     * @return
     */
    @Override
    public Movement getMovementById(String id) {
        return mongoTemplate.findById(new ObjectId(id), Movement.class);
    }

    /**
     * 通过用户id查询动态
     *
     * @param uid
     * @param state
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public PageResult<Movement> getMovementsByCondition(Long uid, Integer state, Long page, Long pagesize) {
        Query query = new Query();
        if(null != uid) {
            query.addCriteria(Criteria.where("userId").is(uid));
        }
        if(null != state) {
            query.addCriteria(Criteria.where("state").is(state));
        }
        long count = mongoTemplate.count(query, Movement.class);
        long start = (page - 1) * pagesize;
        List<Movement> movements = new ArrayList<>();
        if(count > start) {
            query.skip(start).limit(pagesize.intValue()).with(Sort.by(Sort.Direction.DESC, "created"));
            movements = mongoTemplate.find(query, Movement.class);
        }
        return new PageResult<>(page, pagesize, count, movements);
    }

    /**
     * 根据动态id查询动态
     *
     * @param movementId
     * @return
     */
    @Override
    public Movement findById(String movementId) {
        return mongoTemplate.findById(new ObjectId(movementId), Movement.class);
    }

    /**
     * 更新动态状态
     *
     * @param movementId
     * @param state
     */
    @Override
    public void update(String movementId, Integer state) {
        Query query = new Query(Criteria.where("_id").is(new ObjectId(movementId)));
        Update update = new Update();
        update.set("state", state);
        mongoTemplate.updateFirst(query, update, Movement.class);
    }

    /**
     * 动态审核
     *
     * @param movementIds
     * @return
     */
    @Override
    public int audit(List<ObjectId> movementIds, int state) {
        Query query = new Query(Criteria.where("_id").in(movementIds));
        Update update = new Update();
        update.set("state", state);
        UpdateResult updateResult = mongoTemplate.updateMulti(query, update, Movement.class);
        return (int) updateResult.getModifiedCount();
    }
}
